package com.xiaomaoguai.springmvc.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.xiaomaoguai.springmvc.model.AccountModel;

/**
 * @Description :
 * @FileName: DataBindController.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年5月15日 下午4:03:09
 * @Version:V1.00
 */
@Controller
@RequestMapping("/DataBind")
public class DataBindController {

	@RequestMapping(value = { "/parambind" }, method = RequestMethod.GET)
	public ModelAndView toDataView() {
		ModelAndView view = new ModelAndView("parambind", "name", "hello");
		return view;
	}

	@RequestMapping(value = "/parambind", method = RequestMethod.POST)
	public ModelAndView toResult(HttpServletRequest request, @RequestParam(value = "urlParam") String urlParam,
			@RequestParam("formParam") String formParam, @RequestParam("formFile") MultipartFile formFile)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView("parambindresult");  

		FileUtils.copyInputStreamToFile(formFile.getInputStream(), new File("D://888.png"));
		
		// 如果不用注解自动绑定，我们还可以像下面一样手动获取数据
		String urlParam1 = ServletRequestUtils.getStringParameter(request, "urlParam", null);
		String formParam1 = ServletRequestUtils.getStringParameter(request, "formParam", null);
		MultipartFile formFile1 = ((MultipartHttpServletRequest)request).getFile("formFile");
		
		modelAndView.addObject("urlParam1", urlParam1);  
		modelAndView.addObject("formParam1", formParam1);  
		modelAndView.addObject("formFileName1", formFile1.getOriginalFilename());  
		
		modelAndView.addObject("urlParam", urlParam);  
		modelAndView.addObject("formParam", formParam);  
		modelAndView.addObject("formFileName", formFile.getOriginalFilename());
		return modelAndView;
	}
	
	@RequestMapping(value="/modelautobind", method = {RequestMethod.GET})
	public String modelAutoBind(HttpServletRequest request, Model model){
		
		model.addAttribute("accountmodel", new AccountModel());
		return "modelautobind";
	}
	
	@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
	public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
		
		model.addAttribute("accountmodel", accountModel);
		return "modelautobindresult";
	}
	
	@RequestMapping(value="/DataBind/input", method = {RequestMethod.GET})
	public String bindInput(HttpServletRequest request, Model model){
		
		return "modelautobind";
	}

}